#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

void Usage()
{
    cout << "Usage: "
         << "./server port" << endl;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage();
        return 1;
    }

    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        return 2;
    }

    uint16_t port = atoi(argv[1]);

    struct sockaddr_in local;
    local.sin_family = AF_INET;
    local.sin_port = htons(port);
    local.sin_addr.s_addr = INADDR_ANY;

    if (bind(sock, (sockaddr *)&local, sizeof(local)) < 0)
    {
        return 3;
    }

    while (1)
    {
#define NUM 128
        char buf[NUM] = {0};
        struct sockaddr_in peer;
        socklen_t sz = sizeof(peer);
        ssize_t ret = recvfrom(sock, buf, NUM - 1, 0, (sockaddr *)&peer, &sz);

        if (ret > 0)
        {
            buf[ret] = 0;
            cout << "client# " << buf << endl;
            string s;
            FILE* fp = popen(buf, "r");
            char line[1024] = {0};
            while (fgets(line, 1023, fp) != nullptr)
            {
                s += line;
            }
            pclose(fp);
            sendto(sock, s.c_str(), ret, 0, (sockaddr*)&peer, sz);
        }
        else if (ret == 0)
        {
            cout << "对端关闭" << endl;
            return 0;
        }
        else
        {
            return 4;
        }
    }
    return 0;
}